#!/usr/bin/perl -w
use strict;

use Getopt::Long;
use Bio::SeqIO;
use File::Spec;

my $size = 1000;
my $exe = 'blastall';
my $blast = 'blastp';
my $formatdb='formatdb';
my $jobdir = 'jobs';
my $stagedir = 'input';
my $outdir   = 'output';
my $params = '-e 1e-3 -a 2 -m 8';
my ($prefix,$input,$database);
GetOptions('j|job:s' => \$jobdir,
	   'p|prefix:s' => \$prefix,
	   'i|input:s'  => \$input,
	   'd|database:s' => \$database,
	   'id|in|sd:s'      => \$stagedir,
	   'params:s'     => \$params,
	   'o|out|output|od:s' => \$outdir,
	   'b|blast:s'    => \$blast,
	   's|size:s'     => \$size,
	   );
mkdir($jobdir) unless -d $jobdir;
mkdir($stagedir) unless -d $stagedir;
mkdir($outdir) unless -d $outdir;
unless( defined $database ) {
    die("must provide database name\n");
} 

my (undef,undef,$db) = File::Spec->splitpath($database);

unless( -f "$database.phr" || -f "$database.nhr" ) {
    if($blast =~ /blast[px]/ ) {
	`formatdb -i $database -p T`;
    } else {
	`formatdb -i $database -p F`;
    }
}
$database = File::Spec->rel2abs($database);
my $in;
my $i = 0;
my ($fname,$stem,$ext);

unless( defined $input ) {
    $in = Bio::SeqIO->new(-format => 'fasta',
			  -fh     => \*ARGV);
    $stem = 'stdin';
    $fname = 'stdin.fa';
} else {
    $in = Bio::SeqIO->new(-format => 'fasta',
			  -file   => $input);
    (undef,undef,$fname) = File::Spec->splitpath($input);
    ($stem,$ext) = split(/\./,$fname); 
    $input = File::Spec->rel2abs($input);
}


my $n = sprintf("%03d",$i++);
my $jobfile = "$jobdir/$stem-vs-$db.$n.sh";
open(my $jobfh => ">$jobfile") || die "cannot open fh for $jobfile\n";
print $jobfh "#!/bin/bash\n";
my $ofile = File::Spec->rel2abs("$outdir/$stem-vs-$db.$n.$blast.tab");	
my $stagefile = File::Spec->rel2abs("$stagedir/$stem.$n.fa");
my $out = Bio::SeqIO->new(-file   => ">$stagefile",
			  -format => 'fasta');
my $counter = 0;
while( my $seq = $in->next_seq ) {    
    if( $counter > 0 && ($counter % $size) == 0 ) {
	printf $jobfh "$exe -p $blast -i $stagefile -d $database -o $ofile  $params";

	close($jobfh);
	$n = sprintf("%03d",$i++);
	$jobfile = "$jobdir/$stem-vs-$db.$n.sh";
	open($jobfh => ">$jobfile") || die "cannot open $jobfile\n";
	$out = undef;
	$stagefile = File::Spec->rel2abs("$stagedir/$stem.$n.fa");
	$out = Bio::SeqIO->new(-file   => ">$stagefile",
			       -format => 'fasta');
	$ofile = File::Spec->rel2abs("$outdir/$stem-vs-$db.$n.$blast.tab");
    }
    $out->write_seq($seq);
    $counter++;
}
printf $jobfh "$exe -p $blast -i $stagefile -d $database -o $ofile $params";

close($jobfh);
